package thread2;

/**
 * Created with IntelliJ IDEA.
 * Description:针对不同对象加锁，则不会产生锁竞争，那就会导致线程安全问题
 * User: bjc
 * Date: 2025-08-18
 * Time: 20:34
 */
public class ThreadDemo2 {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        //创建两个对象
        Object locker1 = new Object();
        Object locker2 = new Object();


        //创建两个线程，每个线程对count加5W次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //对不同对象加锁
                synchronized (locker1) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //对不同对象加锁
                synchronized (locker2) {
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        //创建了两个对象，结果还是错误的，存在线程安全问题
        System.out.println("count = " + count);
    }
}
